package team.bluepen.supermarket.data.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import team.bluepen.supermarket.kafka.KafkaDeserializer;
import team.bluepen.supermarket.kafka.KafkaSerializer;

import java.beans.ConstructorProperties;
import java.io.IOException;

/**
 * @author RollW
 */
public class ProductIdStatusPair {
    private final long id;
    private final boolean state;
    private final int amount;

    @ConstructorProperties({"id", "state", "amount"})
    public ProductIdStatusPair(long id, boolean state, int amount) {
        this.id = id;
        this.state = state;
        this.amount = amount;
    }

    public long getId() {
        return id;
    }

    public boolean isState() {
        return state;
    }

    public int getAmount() {
        return amount;
    }

    public static KafkaSerializer<ProductIdStatusPair> serializer() {
        return Serial.INSTANCE;
    }

    public static KafkaDeserializer<ProductIdStatusPair> deserializer() {
        return Serial.INSTANCE;
    }

    private static class Serial implements KafkaSerializer<ProductIdStatusPair>, KafkaDeserializer<ProductIdStatusPair> {
        private static final Serial INSTANCE = new Serial();
        private final ObjectMapper mapper = new ObjectMapper();

        private Serial() {
        }

        @Override
        public String serialize(ProductIdStatusPair data) {
            try {
                return mapper.writeValueAsString(data);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public ProductIdStatusPair deserialize(String data) {
            try {
                return mapper.readValue(data, ProductIdStatusPair.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
